<?php namespace App\Http\Services;

use App\FollowIntegral;
use App\Userinfo;
use Auth;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Cookie;
use App\User;

class UserManager
{
    public static function isLogin(Request $request=null){

        if(!isset($_COOKIE['user_token'])){
            if(is_null($request)){
                return false;
            }else{
                $token = !is_null($request->header('user_token'))?$request->header('user_token'):$request->get('user_token');
                if(!is_null($token)){

                    $openid = false;
                    try{
                        $openid = CryptoJSAES::decrypt(str_replace(" ","+",$token),env("AES_KEY"));
                    }catch (\Exception $e){
                        return false;
                    }

                    if(!$openid)
                        return false;

                    $thatUser = User::whereWxOpenid($openid)->first();
                    if(!$thatUser)
                        return false;

                    return $thatUser;
                }else{
                    return false;
                }
            }
        }else{
            $openid = Cookie::get('user_token');

            if(!$openid || is_null($openid))
                return false;

            /** @var User $thatUser */
            $thatUser = User::whereWxOpenid($openid)->first();

            if(!$thatUser)
                return false;

            return $thatUser;
        }
    }
}